<?php
defined('YII_DEBUG') or define('YII_DEBUG', false);
defined('YII_SWOOLE') or define('YII_SWOOLE', true);
defined('PEAR_PATH') or define('PEAR_PATH',__DIR__.'/../../../../pear/common');
require PEAR_PATH . '/vendor/autoload.php';
require PEAR_PATH . '/vendor/yiisoft/yii2/Yii.php';
require __DIR__ . '/../../common/config/bootstrap.php';
require __DIR__ . '/../config/bootstrap.php';
$config = yii\helpers\ArrayHelper::merge(
    require __DIR__ . '/../../common/config/main.php',
    require __DIR__ . '/../config/main.php'
);
$http = new swoole_http_server("0.0.0.0", 9501);

$http->on("start", function ($server) {
    echo "Swoole http server is started at http://127.0.0.1:9501\n";
});

$http->on("request", function (\Swoole\Http\Request $request, \Swoole\Http\Response $response) use($config){
    $_COOKIE = [];
    try{
        if(is_array($request->header))
        foreach($request->header as $k => $v){
            $_SERVER['HTTP_'.strtoupper($k)] = $v;
        }
        if(is_array($request->server))
        foreach($request->server as $k => $v){
            $_SERVER[strtoupper($k)] = $v;
        }
        $_SERVER['HTTP_ORIGIN'] = isset($_SERVER['HTTP_ORIGIN'])?$_SERVER['HTTP_ORIGIN']:'*';
        if(is_array($request->cookie))
        foreach($request->cookie as $k => $v){
            $_COOKIE[$k] = $v;
        }
        (new yii\web\Application($config))->run();
        foreach(Yii::$app->response->cookies as $v){
            $response->cookie($v->name,$v->value,$v->expire);
        }
        foreach(Yii::$app->response->headers as $k => $v){
            $response->header($k,implode(';',$v),true);
        }
        foreach(Yii::$app->response->cookies as $v){
            $response->rawcookie($v->name,$v->value,$v->expire);
        }
        session_destroy();
        $response->end(sprintf("%s\n",Yii::$app->response->content));
    }
    catch(Exception $e){
        $response->end(sprintf("%s\n%s\n",$e->getMessage(),$e->getFile(),$e->getLine()));
    }
});

$http->start();